package com.motu.monstercity.server.game.logichandler;

import com.motu.monstercity.module.common.network.RequestParam;
import com.motu.monstercity.module.common.utility.Constant;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGamePartner.*;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.bag.ItemId;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.partner.*;
import com.motu.monstercity.server.game.commondata.skill.Skill;
import com.motu.monstercity.server.game.commondata.suit.Suit;
import com.motu.monstercity.server.game.commondata.system.SystemConstant;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.log.ThinkingDataManager;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.toolset.ErrorWord;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonArray;

import java.util.ArrayList;
import java.util.List;

public class PartnerHandler {
    //CMD_GAME_PARTNER_LEVEL_UP = 70502; // 升级
    public static Object CMD_GAME_PARTNER_LEVEL_UP(RequestParam clientParam) throws Exception {
        CSGamePartnerLevelUpRequest request = CSGamePartnerLevelUpRequest.parseFrom(clientParam.getData());
        CSGamePartnerLevelUpResponse.Builder response = CSGamePartnerLevelUpResponse.newBuilder();
        long userId = clientParam.getUserId();

        int partnerId = request.getPartnerId();
        boolean isTen = request.getIsTen();// 是否连升10级 道具够升几级就升几级

        UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
        if (userPartner == null) {
            return ErrorWord.BAD_PARAM;// 未获得伙伴
        }
        int curLevel = userPartner.getLevel();// 当前等级
        int maxLevel = userPartner.getMaxLevel();// 最大等级
        if (curLevel == maxLevel) {
            return ErrorWord.ALREADY_MAX;// 已达到最大等级,要先突破
        }
        PartnerLevelUp partnerLevelUp = PartnerManager.getPartnerLevelUp(userPartner.getLevel());
        if (partnerLevelUp == null) {
            return ErrorWord.NOT_DATA;
        }

        int itemId = ItemId.PARTNER_EXP;// 伙伴升级只消耗伙伴经验这个道具
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        long itemNum = BagManager.getUserItemNum(userInfo, itemId);// 总的有多少道具
        if (itemNum < partnerLevelUp.getNeedItem()) {
            return ErrorWord.ITEM_LACK;// 道具最少要够升1级
        }

        UserAffair userAffair = GameUser.getUserAffair(userId);
        UserStage userStage = FightManager.getUserStage(userId);
        if (isTen && !SystemManager.checkModuleOpen(userInfo, userAffair, userStage, SystemConstant.SYSTEM_MODULE_ID_PARTNER_LEVEL_UP_TEN)) {
            return ErrorWord.WRONG_STATUS;// 未解锁连升10级
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        int endLevel = curLevel + 1;// 最后要升到的级数
        if (isTen) {
            if (curLevel + 10 > maxLevel) {
                endLevel = maxLevel;
            } else {
                endLevel = curLevel + 10;
            }
        }

        long subTotal = 0;// 总的要扣除的道具数量
        int addLevel = 0;// 实际升级的级数
        for (int i=curLevel;i<endLevel;i++) {
            PartnerLevelUp entity = PartnerManager.getPartnerLevelUp(i);
            if (itemNum >= entity.getNeedItem()) {
                itemNum = itemNum - entity.getNeedItem();
                subTotal += entity.getNeedItem();
                addLevel++;
            } else {
                break;
            }
        }

        RewardManager.subReward(userInfo, itemId, subTotal, pbUserData, LogType.PARTNER_LEVEL_UP);
        long addPower = userPartner.addLevel(pbUserData, userInfo, userPower, addLevel);// 升级会改变战力,城市收益,需要下发给客户端
        userPartner.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userPartner);
        long newPower = userPower.getPower() + addPower;// 新的总战力
        //System.out.println("aa:" + newPower + " add:" + addPower + " old:" + userPower.getPower());
        userPower.handlePowerChange(pbUserData, userInfo, newPower);

        ProtoDataUtils.updatePBUserData(pbUserData, userPartner);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_10, addLevel);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_10, addLevel);
        int totalLevel = PartnerManager.countTotalLevel(userId);// 总的等级数量
        MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_126, totalLevel);// 更新主线任务,成就,日常任务的进度
        RankActManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_126, addLevel);
        PartnerManager.updateMainTaskNum(pbUserData, userId);// TASK_TYPE_107 = 107;// {1}名干员达到{0}级

        // 数数用户干员等级升级事件
        List<RewardItem> cost = new ArrayList<>();
        cost.add(new RewardItem(itemId, subTotal));
        ThinkingDataManager.pushUserPartnerLevelUpEvent(userInfo, ThinkingDataManager.EVENT_PARTNER_LEVEL_UP_LEVEL, curLevel, curLevel + addLevel, userPartner, cost, isTen);

        return response;
    }

    // CMD_GAME_PARTNER_BREAKTHROUGH = 70503; // 突破提升等级上限
    public static Object CMD_GAME_PARTNER_BREAKTHROUGH(RequestParam clientParam) throws Exception {
        CSGamePartnerBreakthroughRequest request = CSGamePartnerBreakthroughRequest.parseFrom(clientParam.getData());
        CSGamePartnerBreakthroughResponse.Builder response = CSGamePartnerBreakthroughResponse.newBuilder();
        long userId = clientParam.getUserId();

        int partnerId = request.getPartnerId();
        UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
        if (userPartner == null) {
            return ErrorWord.BAD_PARAM;// 未获得伙伴
        }
        int maxLevel = userPartner.getMaxLevel();
        if (userPartner.getLevel() != maxLevel) {
            return ErrorWord.WRONG_STATUS;// 未满级不能进行突破
        }
        PartnerBreakthrough curConfig = PartnerManager.getPartnerBreakthroughByMaxLevel(maxLevel);// 当前这档的突破配置
        PartnerBreakthrough nextConfig = PartnerManager.getNextPartnerBreakthrough(maxLevel);// 下一档的突破配置
        if (curConfig == null || nextConfig == null) {
            return ErrorWord.ALREADY_MAX;// 已达到上限
        }

        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        List<RewardItem> needItem = CommonUtils.takeReawrdItemFromStr(curConfig.getNeedItem());// 需要消耗的道具
        if (!BagManager.checkNeedItemNum(userInfo, needItem)) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.subReward(userInfo, needItem, pbUserData, LogType.PARTNER_BREAKTHROUGH);
        userPartner.putMaxLevel(nextConfig.getMaxLevel());
        long addPower = userPartner.addBreakNum(pbUserData, userInfo, userPower, 1);// 突破会改变战力,城市收益,需要下发给客户端
        userPartner.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userPartner);
        long newPower = userPower.getPower() + addPower;// 新的总战力
        userPower.handlePowerChange(pbUserData, userInfo, newPower);

        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_125, 1);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_125, 1);

        return response;
    }

    // CMD_GAME_PARTNER_SKILL_LEVEL_UP = 70504; // 技能升级,基础技能，星级技能，大世界远征技能
    public static Object CMD_GAME_PARTNER_SKILL_LEVEL_UP(RequestParam clientParam) throws Exception {
        CSGamePartnerSkillLevelUpRequest request = CSGamePartnerSkillLevelUpRequest.parseFrom(clientParam.getData());
        CSGamePartnerSkillLevelUpResponse.Builder response = CSGamePartnerSkillLevelUpResponse.newBuilder();
        long userId = clientParam.getUserId();

        int partnerId = request.getPartnerId();
        int index = request.getIndex();// 第几个技能，第一个传0，第二个传1
        int type = request.getType();//0-表示基础技能，1-星级技能（index 也是从0开始，0表示升级1星的技能），2-大世界远征技能，3-光环技能配置在partnermain的skill_halo

        PartnerMain partnerMain = PartnerManager.getPartnerMain(partnerId);
        if (partnerMain == null) {
            return ErrorWord.NOT_DATA;
        }

        UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
        if (userPartner == null) {
            return ErrorWord.ENTITY_NOT_EXIST;
        }
        int skillId = 0;
        JsonArray levelList = null;
        if (type == 0) {// 基础技能
            skillId = partnerMain.takeSkillBaseList()[index];
            levelList = userPartner.getSkillBaseLevelArray();
        }
        if (type == 1) {// 星级技能（客户端上行的index 也是从0开始，0表示升级已解锁的第一个星级技能, 服务端记的是[0,1,1,1,0,0]，需要+1
            index = index + 1;
            int[] starSkillList = userPartner.takeStarSkillList();// 已解锁的星级技能
            if (index > starSkillList.length) {
                return ErrorWord.WRONG_STATUS;// 未解锁
            }
            skillId = starSkillList[index];
            levelList = userPartner.getSkillStarLevelArray();
        }
        if (type == 2) {// 大世界远征技能
            skillId = partnerMain.takeSkillWorldList()[index];
            levelList = userPartner.getSkillWorldLevelArray();
        }
        if (type == 3) {//光环技能配置在partnermain的skill_halo
            int[] haloSkillList = partnerMain.takeSkillHaloList();
            if (haloSkillList == null || haloSkillList.length == 0 || index >= haloSkillList.length) {
                return ErrorWord.NOT_DATA;// 该干员没有光环技能
            }
            skillId = haloSkillList[index];
            levelList = userPartner.getSkillHaloLevelArray();
        }

        if (skillId == 0 || index >= levelList.size()) {
            return ErrorWord.NOT_DATA;
        }
        int curLevel = levelList.getInteger(index);// 当前等级
        int newLevel = curLevel + 1;

        Skill skill = SkillManager.getSkill(skillId);
        if (skill == null) {
            return ErrorWord.NOT_DATA_1;
        }

        if (skill.getMaxLevel() > 0 && newLevel > skill.getMaxLevel()) {
            return ErrorWord.ALREADY_MAX;//  已达到最大等级
        }

        List<RewardItem> rewardItems = skill.takeLevelUpItems(curLevel);// 消耗的道具数量
        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (!BagManager.checkNeedItemNum(userInfo, rewardItems)) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        UserPower userPower = GameUser.getUserPower(userId);
        int oldTalent = userPartner.takeTalentSkill();// 升级前的技能加成总资质
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.subReward(userInfo, rewardItems, pbUserData, LogType.PARTNER_SKILL_LEVEL_UP);

        levelList.set(index, newLevel);
        if (type == 0) {// 基础技能 会影响自身战力，提供总战力，影响商业建筑的收益
            userPartner.putSkillBaseLevel(levelList.toString());
        }
        if (type == 1) {// 星级技能
            userPartner.putSkillStarLevel(levelList.toString());
        }
        if (type == 2) {// 大世界技能，远征技能 属于具体模块的技能
            userPartner.putSkillWorldLevel(levelList.toString());
        }
        if (type == 3) {// 光环技能
            userPartner.putSkillHaloLevel(levelList.toString());
        }
        PartnerManager.handlePartnerLevelUp(pbUserData, userInfo, userPower, userPartner, skill, newLevel, type);// 处理干员技能升级带来的战力变化，和驻派的商业建筑的收益变化
        userPartner.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userPartner);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_23, 1);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_23, 1);
        int addTalent = userPartner.takeTalentSkill() - oldTalent;// 本次技能升级增加的资质
        if (addTalent > 0) {
            MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_141, addTalent);// 更新主线任务,成就,日常任务的进度
            RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_141, addTalent);
        }

        if (type == 2) {// 大世界技能，远征技能 属于具体模块的技能
            ThinkingDataManager.pushUserWorldSkillLevelUpEvent(userInfo, index + 1, newLevel);// 数数上报数据
        }

        return response;
    }

    // CMD_GAME_PARTNER_SUIT_PUT_ON = 70505; // 服装穿上
    public static Object CMD_GAME_PARTNER_SUIT_PUT_ON(RequestParam clientParam) throws Exception {
        CSGamePartnerSuitPutOnRequest request = CSGamePartnerSuitPutOnRequest.parseFrom(clientParam.getData());
        CSGamePartnerSuitPutOnResponse.Builder response = CSGamePartnerSuitPutOnResponse.newBuilder();
        long userId = clientParam.getUserId();

        int partnerId = request.getPartnerId();
        int suitId = request.getSuitId();
        Suit suit = SuitManager.getSuit(suitId);
        if (suit.getOwnerId() != partnerId) {
            return ErrorWord.WRONG_STATUS;// 这个服装不能穿在这个伙伴身上
        }

        UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
        UserSuit userSuit = SuitManager.getUserSuit(userId, suitId);
        if (userPartner == null || userSuit == null) {
            return ErrorWord.BAD_PARAM;// 未解锁
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        userPartner.putSuitId(suitId);
        userPartner.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userPartner);

        return response;
    }

    // CMD_GAME_PARTNER_WEAPON_LEVEL_UP = 70506; // 武器升级
    public static Object CMD_GAME_PARTNER_WEAPON_LEVEL_UP(RequestParam clientParam) throws Exception {
        CSGamePartnerWeaponLevelUpRequest request = CSGamePartnerWeaponLevelUpRequest.parseFrom(clientParam.getData());
        CSGamePartnerWeaponLevelUpResponse.Builder response = CSGamePartnerWeaponLevelUpResponse.newBuilder();
        long userId = clientParam.getUserId();

        long dbid = request.getDbid();// userweapon表的dbid
        boolean isTen = request.getIsTen();// 是否连升10级
        UserWeapon userWeapon = PartnerManager.getUserWeapon(userId, dbid);
        if (userWeapon == null) {
            return ErrorWord.BAD_PARAM;// 未解锁
        }

        WeaponMain weaponMain = PartnerManager.getWeaponMain(userWeapon.getWeaponId());
        if (weaponMain == null) {
            return ErrorWord.NOT_DATA;
        }
        int curLevel = userWeapon.getLevel();
        int addLevel = isTen ? 10 : 1;

        UserPower userPower = GameUser.getUserPower(userId);
        if (curLevel + addLevel > userWeapon.getMaxLevel(userPower)) {
            return ErrorWord.ALREADY_MAX;// 最大等级
        }
        int itemId = ItemId.WEAPON_LEVEL_UP;
        long subNum = weaponMain.getUpgradeItem() * addLevel;// 需要消耗的数量
        UserInfo userInfo = GameUser.getUserInfo(userId);

        long userItemNum = BagManager.getUserItemNum(userInfo, itemId);
        if (userItemNum < subNum) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.subReward(userInfo, itemId, subNum, pbUserData, LogType.PARTNER_WEAPON_LEVEL_UP);
        userWeapon.addLevel(addLevel);// 等级
        int newTalent = userWeapon.getTalent() + weaponMain.getUpgradeAddTalent() * addLevel;
        userWeapon.putTalent(newTalent);
        userWeapon.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userWeapon);
        if (userWeapon.getPartnerId() > 0) {
            UserPartner userPartner = PartnerManager.getUserPartner(userId, userWeapon.getPartnerId());
            userPartner.updateWeaponAdd(pbUserData, userInfo, userPower, userWeapon);
            userPartner.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userPartner);
        }
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_37, addLevel);// 更新主线任务,成就,日常任务的进度
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_133, addLevel);// 更新主线任务,成就,日常任务的进度
        int totalLevel = PartnerManager.countWeaponLevel(userId);
        MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_185, totalLevel);// 更新主线任务,成就,日常任务的进度
        PartnerManager.updateWeaponTalentTaskNum(pbUserData, userInfo); // 更新111任务
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_37, addLevel);
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_133, addLevel);
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_185, totalLevel);

        // 上报数数
        ThinkingDataManager.pushUserWeaponLevelUpEvent(userInfo, dbid, userWeapon.getWeaponId(), curLevel, curLevel + addLevel, addLevel);


        return response;
    }

    // CMD_GAME_PARTNER_WEAPON_AWAKE = 70507; // 武器觉醒
    public static Object CMD_GAME_PARTNER_WEAPON_AWAKE(RequestParam clientParam) throws Exception {
        CSGamePartnerWeaponAwakeRequest request = CSGamePartnerWeaponAwakeRequest.parseFrom(clientParam.getData());
        CSGamePartnerWeaponAwakeResponse.Builder response = CSGamePartnerWeaponAwakeResponse.newBuilder();
        long userId = clientParam.getUserId();

        long dbid = request.getDbid();// userweapon表的dbid
        UserWeapon userWeapon = PartnerManager.getUserWeapon(userId, dbid);
        if (userWeapon == null) {
            return ErrorWord.BAD_PARAM;// 未解锁
        }

        WeaponMain weaponMain = PartnerManager.getWeaponMain(userWeapon.getWeaponId());
        if (weaponMain == null || weaponMain.getAwakeType() == 0) {
            return ErrorWord.NOT_DATA;// 该武器不能觉醒
        }

        int curAwake = userWeapon.getAwakeNum();// 当前的觉醒等级
        int nexAwake = curAwake + 1;
        WeaponAwake weaponAwakeCur = PartnerManager.getWeaponAwake(curAwake);
        WeaponAwake weaponAwakeNext = PartnerManager.getWeaponAwake(nexAwake);
        if (weaponAwakeCur == null || weaponAwakeNext == null) {
            return ErrorWord.NOT_DATA;
        }

        UserInfo userInfo = GameUser.getUserInfo(userId);
        List<RewardItem> awakeItem = CommonUtils.takeReawrdItemFromStr(weaponAwakeCur.getAwakeItem());
        if (!BagManager.checkNeedItemNum(userInfo, awakeItem)) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserPower userPower = GameUser.getUserPower(userId);
        RewardManager.subReward(userInfo, awakeItem, pbUserData, LogType.PARTNER_WEAPON_AWAKE);
        JsonArray jsonArray = userWeapon.takeAttAdd();
        JsonArray jsonArray2 = userWeapon.takeAttRefresh();
        for (int i=0; i<AllParam.WEAPON_UPGRADE_ADD; i++) {
            jsonArray.add(PartnerManager.takeRandomAtt(false));
            jsonArray2.add("");
        }
        userWeapon.putAttAdd(pbUserData, userInfo, userPower, jsonArray.toString());
        userWeapon.putAttRefresh(jsonArray2.toString());
        userWeapon.addAwakeNum(1);// 增加已觉醒次数
        userWeapon.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userWeapon);

        return response;
    }

    // CMD_GAME_PARTNER_WEAPON_ATT_REFRESH = 70508;// 武器洗练
    public static Object CMD_GAME_PARTNER_WEAPON_ATT_REFRESH(RequestParam clientParam) throws Exception {
        CSGamePartnerWeaponAttRefreshRequest request = CSGamePartnerWeaponAttRefreshRequest.parseFrom(clientParam.getData());
        CSGamePartnerWeaponAttRefreshResponse.Builder response = CSGamePartnerWeaponAttRefreshResponse.newBuilder();
        long userId = clientParam.getUserId();

        long dbid = request.getDbid();// userweapon表的dbid
        int index = request.getIndex();
        boolean isUserItem = request.getIsUseItem();// 是否特殊洗练


        UserWeapon userWeapon = PartnerManager.getUserWeapon(userId, dbid);
        if (userWeapon == null) {
            return ErrorWord.BAD_PARAM;// 未解锁
        }

        WeaponMain weaponMain = PartnerManager.getWeaponMain(userWeapon.getWeaponId());
        if (weaponMain == null) {
            return ErrorWord.NOT_DATA;
        }

        if (index < 1 || index > userWeapon.takeAttAdd().size()) {
            return ErrorWord.BAD_PARAM;// 非法槽位
        }

        int itemId = ItemId.GOLD;
        JsonArray refreshTypeArray = userWeapon.getRefreshTypeArray();
        refreshTypeArray.set(index-1, 1);// 普通洗练
        long itemNum = PartnerManager.takeWeaponRefreshGold(userWeapon.takeRefreshNum(index) + 1);// 金币洗练需要消耗的数量
        if (isUserItem) {// 特殊洗练
            itemId = AllParam.WEAPON_SKILL_MODIFY_SILVER_COST_PARAM[0];// 洗练需要消耗的道具
            itemNum = AllParam.WEAPON_SKILL_MODIFY_SILVER_COST_PARAM[1];// 洗练需要消耗的道具数量
            refreshTypeArray.set(index-1, 2);// 特殊洗练
        }

        UserInfo userInfo = GameUser.getUserInfo(userId);
        if (BagManager.getUserItemNum(userInfo, itemId) < itemNum) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.subReward(userInfo, itemId, itemNum, pbUserData, LogType.PARTNER_WEAPON_REFRESH);
        String attAdd = PartnerManager.takeRandomAtt(isUserItem);

        JsonArray attRefreshArray = userWeapon.takeAttRefresh();
        attRefreshArray.set(index-1, attAdd);
        userWeapon.putAttRefresh(attRefreshArray.toString());

        userWeapon.putRefreshType(refreshTypeArray.toString());
        if (!isUserItem) {
            userWeapon.addRefreshNum(index, 1);// 记录普通洗练的次数
        }
        userWeapon.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userWeapon);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_29, 1);// 更新主线任务,成就,日常任务的进度
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_110, 1);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_29, 1);
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_110, 1);

        return response;
    }

    // CMD_GAME_PARTNER_WEAPON_ATT_REFRESH_ONEKEY = 70514;// 武器洗练一键洗练
    public static Object CMD_GAME_PARTNER_WEAPON_ATT_REFRESH_ONEKEY(RequestParam clientParam) throws Exception {
        CSGamePartnerWeaponAttRefreshOnekeyRequest request = CSGamePartnerWeaponAttRefreshOnekeyRequest.parseFrom(clientParam.getData());
        CSGamePartnerWeaponAttRefreshOnekeyResponse.Builder response = CSGamePartnerWeaponAttRefreshOnekeyResponse.newBuilder();
        long userId = clientParam.getUserId();

        long dbid = request.getDbid();// userweapon表的dbid
        int index = request.getIndex();

        UserWeapon userWeapon = PartnerManager.getUserWeapon(userId, dbid);
        if (userWeapon == null) {
            return ErrorWord.BAD_PARAM;// 未解锁
        }

        if (index < 1 || index > userWeapon.takeAttAdd().size()) {
            return ErrorWord.BAD_PARAM;// 非法槽位
        }

        JsonArray refreshTypeArray = userWeapon.getRefreshTypeArray();
        refreshTypeArray.set(index-1, 3);// 一键洗练

        // 执行逻辑
        userWeapon.putRefreshType(refreshTypeArray.toString());
        userWeapon.update();


        return response;
    }


    // CMD_GAME_PARTNER_WEAPON_ATT_REPLACE = 70509;// 武器洗练结果替换
    public static Object CMD_GAME_PARTNER_WEAPON_ATT_REPLACE(RequestParam clientParam) throws Exception {
        CSGamePartnerWeaponAttReplaceRequest request = CSGamePartnerWeaponAttReplaceRequest.parseFrom(clientParam.getData());
        CSGamePartnerWeaponAttReplaceResponse.Builder response = CSGamePartnerWeaponAttReplaceResponse.newBuilder();
        long userId = clientParam.getUserId();

        long dbid = request.getDbid();// userweapon表的dbid
        int index = request.getIndex();

        UserWeapon userWeapon = PartnerManager.getUserWeapon(userId, dbid);
        if (userWeapon == null) {
            return ErrorWord.BAD_PARAM;// 未解锁
        }

        WeaponMain weaponMain = PartnerManager.getWeaponMain(userWeapon.getWeaponId());
        if (weaponMain == null) {
            return ErrorWord.NOT_DATA;
        }

        if (index < 1 || index > userWeapon.takeAttAdd().size()) {
            return ErrorWord.BAD_PARAM;// 非法槽位
        }

        JsonArray attRefreshArray = userWeapon.takeAttRefresh();
        String attString = attRefreshArray.getString(index - 1);
        if (Tool.isEmpty(attString)) {
            return ErrorWord.WRONG_STATUS;//  未洗练
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        JsonArray attAddArray = userWeapon.takeAttAdd();
        JsonArray attAddArrayBefore = userWeapon.takeAttAdd();// 替换前的属性加成列表 发数数用
        attAddArray.set(index-1, attString);
        attRefreshArray.set(index-1, "");// 清空洗练结果
        userWeapon.putAttAdd(pbUserData, userInfo, userPower, attAddArray.toString());
        userWeapon.putAttRefresh(attRefreshArray.toString());

        userWeapon.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userWeapon);

        // 上报数数
        JsonArray refreshTypeArray = userWeapon.getRefreshTypeArray();
        ThinkingDataManager.pushUserWeaponRefreshEvent(userInfo, dbid, userWeapon.getWeaponId(), refreshTypeArray.getInteger(index-1), attAddArrayBefore, attAddArray);

        int total = PartnerManager.countTotalAttActiveNum(userId);// 当前属性生效的数量,计算成就用
        MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_171, total);// 更新主线任务,成就,日常任务的进度
        RankActManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_171, total);

        return response;
    }

    // CMD_GAME_PARTNER_WEAPON_RECYCLE = 70510;// 武器回收
    public static Object CMD_GAME_PARTNER_WEAPON_RECYCLE(RequestParam clientParam) throws Exception {
        CSGamePartnerWeaponRecycleRequest request = CSGamePartnerWeaponRecycleRequest.parseFrom(clientParam.getData());
        CSGamePartnerWeaponRecycleResponse.Builder response = CSGamePartnerWeaponRecycleResponse.newBuilder();
        long userId = clientParam.getUserId();

        List<UserWeapon> list = new ArrayList<>();
        for (long dbid : request.getDbidListList()) {
            UserWeapon userWeapon = PartnerManager.getUserWeapon(userId, dbid);
            if (userWeapon == null) {
                return ErrorWord.BAD_PARAM;// 未解锁
            }
            WeaponMain weaponMain = PartnerManager.getWeaponMain(userWeapon.getWeaponId());
            if (weaponMain == null) {
                return ErrorWord.NOT_DATA;
            }

            if (!weaponMain.isCanRecycle() || userWeapon.takeIsPutOn()) {
                return ErrorWord.WRONG_STATUS;//  该武器无法进行回收
            }
            list.add(userWeapon);
        }


        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserInfo userInfo = GameUser.getUserInfo(userId);
        for (int i=0; i<list.size(); i++) {
            UserWeapon userWeapon = list.get(i);
            List<RewardItem> rewardItems = PartnerManager.takeRecycleReward(userWeapon);
            RewardManager.addReward(userInfo, rewardItems, pbUserData, LogType.PARTNER_WEAPON_RECYCLE,userWeapon.getWeaponId(),userWeapon.getId());
            userWeapon.delete();
            ProtoDataUtils.deletePBUserData(pbUserData, userWeapon);
        }

        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_173, list.size());// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_173, list.size());

        return response;
    }

    // CMD_GAME_PARTNER_WEAPON_PUT_ON = 70507; // 装备武器
    public static Object CMD_GAME_PARTNER_WEAPON_PUT_ON(RequestParam clientParam) throws Exception {
        CSGamePartnerWeaponPutOnRequest request = CSGamePartnerWeaponPutOnRequest.parseFrom(clientParam.getData());
        CSGamePartnerWeaponPutOnResponse.Builder response = CSGamePartnerWeaponPutOnResponse.newBuilder();
        long userId = clientParam.getUserId();

        int partnerId = request.getPartnerId();
        long weaponDbidTarget = request.getDbid();
        UserPartner userPartnerSelf = PartnerManager.getUserPartner(userId, partnerId);
        UserWeapon userWeaponTarget = PartnerManager.getUserWeapon(userId, weaponDbidTarget);
        if (userPartnerSelf == null || userWeaponTarget == null) {
            return ErrorWord.WRONG_STATUS;// 未解锁
        }

        long weaponDbidSelf = userPartnerSelf.getWeaponDbid();// 原来的武器Id
        if (weaponDbidSelf == weaponDbidTarget) {
            return ErrorWord.REPEATED_OPERATION;// 这个武器已经装备在这个干员身上了, 没有发生变化
        }

        // 执行逻辑
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        PBUserData.Builder pbUserData = response.getUserBuilder();
        UserPartner userPartnerTarget = PartnerManager.getUserPartner(userId, userWeaponTarget.getPartnerId());

        // 更新目标武器的信息
        userWeaponTarget.putIsPutOn(1);
        userWeaponTarget.putPartnerId(partnerId);
        userWeaponTarget.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userWeaponTarget);

        // 更新原来武器的信息
        UserWeapon userWeaponSelf = PartnerManager.getUserWeapon(userId, weaponDbidSelf);
        if (userWeaponSelf != null) {// 原来有装备武器
            if (userPartnerTarget != null) {// 换到对方身上
                userWeaponSelf.putIsPutOn(1);
                userWeaponSelf.putPartnerId(userPartnerTarget.getPartnerId());
            } else {// 否则就是脱下
                userWeaponSelf.putIsPutOn(0);
                userWeaponSelf.putPartnerId(0);
            }
            userWeaponSelf.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userWeaponSelf);
        }

        // 更新原来的武器, 和交换干员的信息
        long addTotal = userPartnerSelf.getUpdateWeaponAdd(pbUserData, userInfo, userPower, userWeaponTarget);// 武器加成有变动,weapondbid这个字段,装备或是卸下武器 返回战力变更的值
        userPartnerSelf.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userPartnerSelf);
        if (userPartnerTarget != null) {
            addTotal += userPartnerTarget.getUpdateWeaponAdd(pbUserData, userInfo, userPower, userWeaponSelf);
            userPartnerTarget.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userPartnerTarget);
        }

        // 更新玩家的总战力
        if (addTotal != 0) {// 战力有变动
            long newPower = userPower.getPower() + addTotal;// 玩家的基础战力增加
            userPower.handlePowerChange(pbUserData, userInfo, newPower);// 更新玩家的总战力
        }

        int total = PartnerManager.countPartnerWeapon(userId);// 统计装备了武器的干员总数量
        MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_138, total);// 更新主线任务,成就,日常任务的进度
        RankActManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_138, total);

        int total2 = PartnerManager.countTotalAttActiveNum(userId);// 当前属性生效的数量,计算成就用
        MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_171, total2);// 更新主线任务,成就,日常任务的进度
        RankActManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_171, total2);

        return response;
    }

    // CMD_GAME_PARTNER_WEAPON_PUT_OFF = 70508; // 卸下武器
    public static Object CMD_GAME_PARTNER_WEAPON_PUT_OFF(RequestParam clientParam) throws Exception {
        CSGamePartnerWeaponPutOffRequest request = CSGamePartnerWeaponPutOffRequest.parseFrom(clientParam.getData());
        CSGamePartnerWeaponPutOffResponse.Builder response = CSGamePartnerWeaponPutOffResponse.newBuilder();
        long userId = clientParam.getUserId();

        int partnerId = request.getPartnerId();
        UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
        if (userPartner == null || userPartner.getWeaponDbid() == 0) {
            return ErrorWord.WRONG_STATUS;// 未解锁或是未装备武器
        }
        long weanponDbid = userPartner.getWeaponDbid();
        UserWeapon userWeapon = PartnerManager.getUserWeapon(userId, weanponDbid);
        if (userWeapon == null) {
            return ErrorWord.WRONG_STATUS;//
        }

        // 执行逻辑
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserPower userPower = GameUser.getUserPower(userId);
        PBUserData.Builder pbUserData = response.getUserBuilder();
        userPartner.updateWeaponAdd(pbUserData, userInfo, userPower, null);
        userPartner.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userPartner);

        userWeapon.putIsPutOn(0);
        userWeapon.putPartnerId(0);
        userWeapon.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userWeapon);

        return response;
    }

    // CMD_GAME_PARTNER_STAR_UP = 70513; // 升星
    public static Object CMD_GAME_PARTNER_STAR_UP(RequestParam clientParam) throws Exception {
        CSGamePartnerStarUpRequest request = CSGamePartnerStarUpRequest.parseFrom(clientParam.getData());
        CSGamePartnerStarUpResponse.Builder response = CSGamePartnerStarUpResponse.newBuilder();
        long userId = clientParam.getUserId();

        int partnerId = request.getPartnerId();
        PartnerMain partnerMain = PartnerManager.getPartnerMain(partnerId);
        if (partnerMain == null || partnerMain.getUnlockStunt() == 0) {
            return ErrorWord.NOT_DATA;// 该干员不能升星
        }

        UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
        if (userPartner == null) {
            return ErrorWord.BAD_PARAM;// 未获得伙伴
        }
        int curStar = userPartner.getStar();
        int nextStar = curStar + 1;
        int quality = userPartner.takeQuality();// 品质
        PartnerStar curConfig = PartnerManager.getPartnerStar(curStar, quality);//
        PartnerStar nextConfig = PartnerManager.getPartnerStar(nextStar, quality);//
        if (curConfig == null || nextConfig == null) {
            return ErrorWord.ALREADY_MAX;// 已达到上限
        }

        if (userPartner.getLevel() < curConfig.getNeedLevel()) {
            return ErrorWord.WRONG_STATUS;//  等级不足
        }

        UserInfo userInfo = GameUser.getUserInfo(userId);
        int itemId = userPartner.takeChipId();// 消耗的碎片Id
        long itemNum = curConfig.getNeedItemNum();// 需要的数量
        if (BagManager.getUserItemNum(userInfo, itemId) < itemNum) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        int oldStarLevel = userPartner.takeSkillExStuntLevel();// 升级之前专属技能是几级
        RewardManager.subReward(userInfo, itemId, itemNum, pbUserData, LogType.PARTNER_STAR_UP);
        userPartner.putStar(nextStar);
        int newStarLevel = userPartner.takeSkillExStuntLevel();//  升级之后专属技能是几级

        // 解锁星级技能
        if (nextConfig.getSkillId() > 0) {
            JsonArray jsonArray = userPartner.getSkillStarLevelArray();
            jsonArray.set(newStarLevel, 1);// 如解锁到2星，则技能等级[0，1,1,0,0,0],0星，1星--5星
            userPartner.putSkillStarLevel(jsonArray.toString());
        }

        UserPower userPower = GameUser.getUserPower(userId);
        long addValue = userPartner.reCountPower(userInfo, userPower);// 升星会提高干员战力,需要重算
        userPartner.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userPartner);

        // 本次升级有提升星数， （专属技能升级）
        if (newStarLevel > oldStarLevel) {
            PartnerManager.handlePartnerExstuntLevelUp(pbUserData, userInfo, userPower, userPartner, partnerMain.takeSkillExStuntList(), newStarLevel);
        }

        long newPower = userPower.getPower() + addValue;
        userPower.handlePowerChange(pbUserData, userInfo, newPower);

        // 数数用户干员升星事件
        List<RewardItem> needItem = new ArrayList<>();
        RewardItem rewardItem = new RewardItem(itemId, itemNum);
        needItem.add(rewardItem);
        ThinkingDataManager.pushUserPartnerLevelUpEvent(userInfo, ThinkingDataManager.EVENT_PARTNER_LEVEL_UP_STAR, curStar, nextStar, userPartner, needItem, false);

        return response;
    }

    // CMD_GAME_PARTNER_CHIP_EXCHANGE = 70515;// 英雄招募卡可兑换成对应英雄的碎片，英雄的品质不同，可兑换的数量也不同
    public static Object CMD_GAME_PARTNER_CHIP_EXCHANGE(RequestParam clientParam) throws Exception {
        CSGamePartnerChipExchangeRequest request = CSGamePartnerChipExchangeRequest.parseFrom(clientParam.getData());
        CSGamePartnerChipExchangeResponse.Builder response = CSGamePartnerChipExchangeResponse.newBuilder();
        long userId = clientParam.getUserId();

        int partnerId = request.getPartnerId();
        int num = request.getNum();
        if (num <= 0 || num > 999) {
            return ErrorWord.BAD_PARAM;
        }
        PartnerMain partnerMain = PartnerManager.getPartnerMain(partnerId);
        if (partnerMain == null) {
            return ErrorWord.NOT_DATA;//
        }

        UserPartner userPartner = PartnerManager.getUserPartner(userId, partnerId);
        if (userPartner == null) {
            return ErrorWord.BAD_PARAM;// 未获得伙伴
        }

        UserInfo userInfo = GameUser.getUserInfo(userId);
        int itemId = ItemId.RECRUIT_ITEM;// 招募卡

        if (BagManager.getUserItemNum(userInfo, itemId) < num) {
            return ErrorWord.ITEM_LACK;// 道具不足
        }

        // 执行逻辑
        PBUserData.Builder pbUserData = response.getUserBuilder();
        RewardManager.subReward(userInfo, itemId, num, pbUserData, LogType.PARTNER_CHIP_EXCHANGE);

        int itemIdReward = userPartner.takeChipId();// 获得对应干员的碎片
        long addNum = AllParam.HERO_DEBRIS_NUM[userPartner.takeQuality() - 1];//{50, 30, 20, 9, 5};//英雄招募卡可兑换成对应英雄的碎片，英雄的品质不同，可兑换的数量也不同
        RewardManager.addReward(userInfo, itemIdReward, addNum * num, pbUserData, LogType.PARTNER_CHIP_EXCHANGE);

        return response;
    }
}
